package com.dorm.mybatis.service;

import com.dorm.mybatis.mapper.CountryMapper;
import com.dorm.mybatis.model.Country;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.io.InputStream;

@Service
public class CountryService {

    private SqlSession sqlSession;

    @PostConstruct
    public void init() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory =
                new SqlSessionFactoryBuilder().build(inputStream);
        sqlSession = sqlSessionFactory.openSession(true);
        save(new Country().setId(1).setCountryCode("cc").setCountryName("ss").setVersion(2));
    }

    private CountryMapper getMapper() {
        return sqlSession.getMapper(CountryMapper.class);
    }

    public boolean save(Country country) {
        return getMapper().save(country) == 1;
    }

    public Country selectById(Integer id) {
        return getMapper().selectOne(id);
    }


}
